package util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;

public class HttpClientUtility {
	
	public static final String RESPONSE_DECODING_CHARSET = "UTF-8";
	
	public static String getStrByHttp(URI uri) throws ClientProtocolException, IOException {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			

			/*
			 * setProxy(optional)
			 */
			if(LocalProxy.USED) {
				HttpHost proxy = new HttpHost(LocalProxy.HOST, LocalProxy.PORT);
				httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
						proxy);
			}
			
			/*
			 * request and response
			 */
			HttpGet httpget = new HttpGet(uri);

			/* use BasicResponseHandler to get NC response string */

			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			
//			Logging.logInfo("httpclient request charset: " 
//					+ httpclient.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));
			
			String responseBody = httpclient.execute(httpget, responseHandler);
			responseBody = new String(responseBody.getBytes(
					httpclient.getParams().getParameter(
							CoreProtocolPNames.HTTP_CONTENT_CHARSET).toString()),
					RESPONSE_DECODING_CHARSET);
			return responseBody;
		} finally{
			httpclient.getConnectionManager().shutdown();
		}
	}
	
	public static void main(String[] args) throws ClientProtocolException, IOException, URISyntaxException {
		String url = "http://www.google.com/search" + "?keywords=" + "b a";			
		GetMethod gm = new GetMethod(url);
		HttpClient httpclient = new HttpClient();
		HttpClientParams params = new HttpClientParams();
		
		httpclient.setParams(params);

		int result = httpclient.executeMethod(gm);
	}

}
